package com.example.amoocspringboot.service.impl;

import com.example.amoocspringboot.ResponseResult;
import com.example.amoocspringboot.entity.LoginUser;
import com.example.amoocspringboot.entity.User;
import com.example.amoocspringboot.service.LoginService;
import com.example.amoocspringboot.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;

    @Autowired
    public LoginServiceImpl(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public ResponseResult<Map<String, Object>> login(User user) {
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());

            Authentication authenticate = authenticationManager.authenticate(authenticationToken);

            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            String userId = loginUser.getUser().getId().toString();
            System.out.println(userId);
            Map<String, Object> map = new HashMap<>();
            map.put("token", JwtUtil.createToken(userId, "Amooc disk token"));
            return new ResponseResult<>(200, "success", map);

        } catch (BadCredentialsException e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "用户名或密码错误");
            return new ResponseResult<>(401, "认证失败", errorMap);
        } catch (Exception e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return new ResponseResult<>(500, "登录失败", errorMap);
        }
    }
}